package com.note.simpleshop.module.user.auth;

import com.note.simpleshop.entity.TbToken;
import com.note.simpleshop.module.user.controller.LoginController;
import com.note.simpleshop.module.user.service.TokeService;
import com.note.simpleshop.utils.DateUtil;
import com.note.simpleshop.utils.IdGenerator;
import com.note.simpleshop.utils.TokenGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

@Component
public class MysqlTokenManager implements TokenManager {
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    //token过期时间为7天
    public final Integer TOKEN_EXPIRE =7*24*60 * 60 * 1000;
    @Autowired
    private TokeService tokenService;
    @Override
    public String generateToken(String userId) {
        TbToken model=new TbToken();
        long now=System.currentTimeMillis();
        model.setId(IdGenerator.id());
        model.setCreateTime(new Timestamp(now));
        model.setExpireTime(new Timestamp(now+TOKEN_EXPIRE));
        model.setUserId(userId);
        model.setToken(TokenGenerator.generatorToken());
        tokenService.save(model);
        return model.getToken();
    }
    @Override
    public boolean checkToken(String token) {
        TbToken tokenModel=tokenService.findByToken(token);
        if (tokenModel!=null && tokenModel.getExpireTime().after(DateUtil.getTimestamp()))
        {
            return true;// token没有过期
        } else
        {
            // token不存在或者token过期
            return false;
        }
    }
    @Override
    public void deleteToken(String token) {
        tokenService.delete(token);
    }
    @Override
    public Object getObject(String token) {
        TbToken model=tokenService.findByToken(token);
        return model;
    }
}
